package com.rocching.easychat.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.rocching.easychat.EasyChatApp;
import com.rocching.easychat.entity.DocumentEntity;

public class EasyChatSQLiteOpenHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "easy_chat.db";
    private static final int DATABASE_VERSION = 6;
    private static EasyChatSQLiteOpenHelper instance;

    public EasyChatSQLiteOpenHelper(@Nullable Context context, @Nullable String name, int version) {
        super(context, name, null, version);
    }

    public static EasyChatSQLiteOpenHelper getInstance() {
        if (instance == null) {
            instance = new EasyChatSQLiteOpenHelper(EasyChatApp.getContext(), DATABASE_NAME, DATABASE_VERSION);
        }
        return instance;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        createTables(db);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }

    public void closeDb() {
        if (instance != null) {
            try {
                SQLiteDatabase db = instance.getWritableDatabase();
                db.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            instance = null;
        }
    }

    private void createTables(SQLiteDatabase db) {
        String create_sql = "CREATE TABLE IF NOT EXISTS " + DocumentEntity.TABLE_NAME + " (" +
                DocumentEntity.FIELD_NAME_ID + " INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT," +
                DocumentEntity.FIELD_NAME_OBJECT_ID + " TEXT NOT NULL," +
                DocumentEntity.FIELD_NAME_TYPE + " TEXT NOT NULL," +
                DocumentEntity.FIELD_NAME_CONTENT + " TEXT " +
                ")";
        db.execSQL(create_sql);
    }
}
